package com.front.web.commons;


import com.bootdo.common.redisUtils.JedisUtils;
import com.bootdo.common.utils.IPUtils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.redis.RedisUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 重复提交aop
 * @data: 2019-03-26 16:39
 **/
@Aspect
@Component
public class AvoidRepeatableCommitAspect {

    @Autowired
    private RedisUtil redisUtil;
    /**
     * @param point
     */
    @Around("@annotation(com.front.web.commons.AvoidRepeatableCommit)")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        HttpServletRequest request  = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String ip = IPUtils.getIpAddr(request);
        //获取注解
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        //目标类、方法
        String className = method.getDeclaringClass().getName();
        String name = method.getName();
        String ipKey = String.format("%s#%s",className,name);
        int hashCode = Math.abs(ipKey.hashCode());

        String key = Constants.REDIS_ROOT+String.format("%s_%d",ip,hashCode);

        /*log.info("ipKey={},hashCode={},key={}",ipKey,hashCode,key);*/
        AvoidRepeatableCommit avoidRepeatableCommit =  method.getAnnotation(AvoidRepeatableCommit.class);
        Long timeout = avoidRepeatableCommit.timeout();
        if (timeout < 0){
            timeout = 3*Constants.SECOND;
        }
      /*  String value = (String) redisTemplate.opsForValue().get(key);*/
/*        JedisUtils.del(key);*/
        String value = (String) redisUtil.get(key);
        if (StringUtils.isNotBlank(value)){

            return R.error("请勿重复提交");
        }
        redisUtil.set(key, UUID.randomUUID().toString(),timeout.intValue());
        //执行方法
        Object object = point.proceed();

        return object;
    }

}
